import { AvatarUpload } from '@/components/CustomUpload';
import ProForm, { ProFormRadio, ProFormText } from '@ant-design/pro-form';
import { Row, Col, message } from 'antd';
import React, { useRef } from 'react';
import { useIntl, useModel } from 'umi';
import type {
    ProFormInstance,
} from '@ant-design/pro-form';
import {
    getApiAccountSettings as accountSettings,
    postApiAccountSettings as updateAccountSettings,
    getApiAccountSettingsValueCheck as valueCheck,
} from '@/services/furion-cms/Account';
import ProCard from '@ant-design/pro-card';

const BaseView: React.FC = () => {
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();

    const formRef = useRef<ProFormInstance<API.AccountSettingsDto>>();
    const { initialState, setInitialState } = useModel('@@initialState');

    const remoteValidator = async (field: string, value: any) => {
        try {
            const { success, errorMessage } = await valueCheck({
                fieldName: field,
                fieldValue: value,
            }, { skipErrorHandler: true });
            if (!success) {
                return Promise.reject(errorMessage);
            }
            return Promise.resolve();
        }
        catch (err) {
            return Promise.reject(err);
        }
    }

    return (
        <ProCard title={<span style={{
            fontSize: 20
        }}>{intl.formatMessage({
            id: 'pages.account.settings.base',
            defaultMessage: '个人资料'
        })}</span>}>
            <ProForm<API.AccountSettingsDto>
                formRef={formRef}
                request={() => {
                    return accountSettings()
                        .then(({ data }) => ({ ...data }));
                }}
                onFinish={(values) => {
                    console.log('accountSettings-Finish', values);
                    return updateAccountSettings(values as API.AccountSettingsModifyDto)
                        .then(async () => {
                            const userInfo = await initialState?.fetchUserInfo?.();
                            await setInitialState((s) => ({
                                ...s,
                                currentUser: userInfo
                            }));
                            message.success(intl.formatMessage({
                                id: 'pages.common.success',
                                defaultMessage: '保存成功'
                            }));
                        });
                }}
            >
                {/* 基础配置 */}
                <Row gutter={24}>
                    <Col span={10}>
                        <ProFormText
                            name="nickName"
                            label={intl.formatMessage({
                                id: 'pages.user.detail.input.nickName',
                                defaultMessage: '用户昵称'
                            })}
                            tooltip={intl.formatMessage({
                                id: 'pages.user.detail.input.nickName.tip',
                                defaultMessage: '用户昵称不允许重复'
                            })}
                            placeholder={intl.formatMessage({
                                id: 'pages.user.detail.input.nickName.placeholder',
                                defaultMessage: '请输入您要使用的昵称'
                            })}
                            validateTrigger={['onChange', 'onBlur']}
                            required
                            rules={[
                                {
                                    required: true,
                                    message: intl.formatMessage({
                                        id: 'pages.user.detail.input.nickName.rules',
                                        defaultMessage: '用户昵称必填'
                                    }),
                                    validateTrigger: 'onChange',
                                    validator: (rule, value) => {
                                        if (!value) {
                                            return Promise.reject(rule.message);
                                        }
                                        return Promise.resolve();
                                    }
                                },
                                {
                                    validator: (_, value) => {
                                        if (value) {
                                            return remoteValidator('NickName', value);
                                        }
                                        else {
                                            return Promise.resolve();
                                        }
                                    },
                                    validateTrigger: 'onBlur'
                                }
                            ]}
                        />
                        <ProFormRadio.Group
                            name="gender"
                            label={intl.formatMessage({
                                id: 'pages.user.detail.input.gender',
                                defaultMessage: '性别'
                            })}
                            options={[
                                {
                                    label: intl.formatMessage({
                                        id: 'pages.user.detail.input.gender.male',
                                        defaultMessage: '男'
                                    }),
                                    value: 1,
                                },
                                {
                                    label: intl.formatMessage({
                                        id: 'pages.user.detail.input.gender.female',
                                        defaultMessage: '女'
                                    }),
                                    value: 2,
                                },
                            ]}
                        />
                        <ProFormText
                            name="email"
                            label={intl.formatMessage({
                                id: 'pages.user.detail.input.email',
                                defaultMessage: '电子邮件'
                            })}
                            placeholder=""
                            validateTrigger={['onChange', 'onBlur']}
                            rules={[
                                {
                                    pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
                                    message: intl.formatMessage({
                                        id: 'pages.user.detail.input.email.rules',
                                        defaultMessage: '电子邮件格式错误!'
                                    }),
                                    validateTrigger: 'onChange'
                                },
                                {
                                    validator: (_, value) => {
                                        if (value) {
                                            return remoteValidator('Email', value);
                                        }
                                        else {
                                            return Promise.resolve();
                                        }
                                    },
                                    validateTrigger: 'onBlur'
                                }
                            ]}
                        />
                        <ProFormText
                            name="phoneNumber"
                            label={intl.formatMessage({
                                id: 'pages.user.detail.input.phoneNumber',
                                defaultMessage: '手机号'
                            })}
                            placeholder=""
                            validateTrigger={['onChange', 'onBlur']}
                            rules={[
                                {
                                    pattern: /^1\d{10}$/,
                                    message: intl.formatMessage({
                                        id: 'pages.user.detail.input.phoneNumber.rules',
                                        defaultMessage: '手机号格式错误!'
                                    }),
                                    validateTrigger: 'onChange'
                                },
                                {
                                    validator: (_, value) => {
                                        if (value) {
                                            return remoteValidator('PhoneNumber', value);
                                        }
                                        else {
                                            return Promise.resolve();
                                        }
                                    },
                                    validateTrigger: 'onBlur'
                                }
                            ]}
                        />
                    </Col>
                    <Col span={14}>
                        <ProForm.Item label={intl.formatMessage({
                            id: 'pages.user.detail.input.avatar',
                            defaultMessage: '头像'
                        })} name="avatar" valuePropName="src">
                            <AvatarUpload onChange={fileUri => formRef.current?.setFieldsValue({
                                avatar: fileUri
                            })} />
                        </ProForm.Item>
                    </Col>
                </Row>
            </ProForm>
        </ProCard>)
}

export default BaseView;